package com.tuoyu.peopletest.view.ac;

import android.app.DatePickerDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.tuoyu.peopletest.R;
import com.tuoyu.peopletest.adapter.PDTestListAdapter;
import com.tuoyu.peopletest.common.Constant;
import com.tuoyu.peopletest.entity.DataBean;
import com.tuoyu.peopletest.model.DataModel;
import com.tuoyu.peopletest.model.UserModel;
import com.tuoyu.peopletest.scinterface.OnItemDataListener;
import com.tuoyu.peopletest.utils.MyThreadPoolUtils;
import com.tuoyu.peopletest.utils.SCLogUtils;
import com.tuoyu.peopletest.utils.SCTimeUtils;
import com.tuoyu.peopletest.view.custom.MyRecyclerView;
import com.tuoyu.peopletest.view.custom.TitleOrderView;
import com.tuoyu.peopletest.view.pop.TestDetailDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * 用户列表
 */
public class QueryListActivity extends BaseActivity implements OnItemDataListener<DataBean>,
        View.OnClickListener, TextView.OnEditorActionListener {
    private MyRecyclerView myRecyclerView;
    private int mPage = 1;
    private int mPageMax = 100;
    private List<DataBean> mDataList;
    private PDTestListAdapter mAdapter;
    private LinearLayoutManager linearLayoutManager;
    private boolean isHaveNextPage = false;
    private UserModel userModel;
    private View vSearch;
    private View vSearchMain;
    private EditText etSearch;
    private TextView tvStartTime;
    private TextView tvEndTime;
    private TextView tvToday;
    private TextView tvOneWeek;
    private TextView tvOneMonth;
    private View vSelect;
    private int type;
    private DataModel dataModel;
    private long mStartTime;
    private long mEndTime;
    private TitleOrderView vTitleDate;
    private boolean isDateOrderUp;

    @Override
    public void initContentView() {
        setContentView(R.layout.activity_query_list);
        //沉浸式
        ImmersionBar.with(this).init();
        View vStatusTop = vBaseMain.findViewById(R.id.v_status_top);
        ViewGroup.LayoutParams layoutParams = vStatusTop.getLayoutParams();
        layoutParams.height = BarUtils.getStatusBarHeight();
        //SCLogUtils.e(TAG,"layoutParams.height="+layoutParams.height);
        vStatusTop.setLayoutParams(layoutParams);

    }

    @Override
    public void initChildView() {
        setTitle(R.id.tv_title, R.string.sc_t_query);
        setBackEvent(R.id.iv_back);
        myRecyclerView = findViewById(R.id.rv_testList);
        vSearch = findViewById(R.id.v_title_search);
        vSearchMain = findViewById(R.id.v_search_main);
        vSearchMain.setVisibility(View.GONE);
        etSearch = findViewById(R.id.et_search);

        tvStartTime = findViewById(R.id.tv_start_time);
        tvEndTime = findViewById(R.id.tv_end_time);
        tvToday = findViewById(R.id.tv_today);
        tvOneWeek = findViewById(R.id.tv_one_week);
        tvOneMonth = findViewById(R.id.tv_one_month);

        vTitleDate = findViewById(R.id.v_title_data);

        if(Constant.isShowArea) {
            findViewById(R.id.v_title_select_area1).setVisibility(View.VISIBLE);
            findViewById(R.id.v_title_select_area2).setVisibility(View.VISIBLE);
        }else{
            findViewById(R.id.v_title_select_area1).setVisibility(View.GONE);
            findViewById(R.id.v_title_select_area2).setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        super.initData();
        //当前时间
        tvStartTime.setText(SCTimeUtils.getFormatData11(System.currentTimeMillis()));
        tvEndTime.setText(SCTimeUtils.getFormatData11(System.currentTimeMillis()));

        userModel = UserModel.get();
        dataModel = DataModel.get();
        mDataList = new ArrayList<>();
        mAdapter = new PDTestListAdapter(this, mDataList, true);
        myRecyclerView.setAdapter(mAdapter);
        linearLayoutManager = (LinearLayoutManager) myRecyclerView.getLayoutManager();


        queryToady();
    }

    @Override
    public void initListener() {
        super.initListener();
        vTitleDate.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        tvToday.setOnClickListener(this);
        tvOneWeek.setOnClickListener(this);
        tvOneMonth.setOnClickListener(this);

        vSearch.setOnClickListener(this);
        findViewById(R.id.v_search_ok).setOnClickListener(this);
        etSearch.setOnEditorActionListener(this);


        mAdapter.setItemClickListener(this);

    }


    @Override
    public void onItemData(DataBean data, int position) {
            //详情
        TestDetailDialog  dialog = (TestDetailDialog) new XPopup.Builder(QueryListActivity.this)
                .dismissOnTouchOutside(true)
                .asCustom(new TestDetailDialog(QueryListActivity.this,data))
                .show();


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.v_title_search:
                if (vSearchMain.isShown()) {
                    vSearchMain.setVisibility(View.GONE);
                } else {
                    vSearchMain.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.v_search_ok:
                //确定搜索
                search();
                break;
            case R.id.tv_start_time:
                type = 0;
                showDataSelect(v);
                break;
            case R.id.tv_end_time:
                type = 1;
                showDataSelect(v);
                break;
            case R.id.tv_today:

                queryToady();
                break;
            case R.id.tv_one_week:
                long l = System.currentTimeMillis();
                mEndTime = SCTimeUtils.getSdf_for11_01(SCTimeUtils.getFormatData11(l)+" 23:59:59");

                mStartTime = mEndTime - 7*24*3600*1000;
                startQuery(mStartTime,mEndTime);
                break;
            case R.id.tv_one_month:
                //一个月
                mEndTime = SCTimeUtils.getSdf_for11_01(SCTimeUtils.getFormatData11(System.currentTimeMillis())+" 23:59:59");

                //mStartTime = mEndTime - 29*24*3600*1000;
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date(mEndTime));
                int day01 = calendar.get(Calendar.DAY_OF_YEAR);
                calendar.set(Calendar.DAY_OF_YEAR, day01 - 31);
                mStartTime = calendar.getTime().getTime();
                startQuery(mStartTime,mEndTime);
                break;
            case R.id.v_title_data:
                //点击时间排序
                vTitleDate.setOrderRestore();
                if (isDateOrderUp) {
                    isDateOrderUp = false;
                    //集合排序
                    Collections.sort(mDataList, new CompartorOrder(12));
                    vTitleDate.setOrderDown();
                    mAdapter.notifyDataSetChanged();

                } else {
                    isDateOrderUp = true;
                    Collections.sort(mDataList, new CompartorOrder(11));
                    vTitleDate.setOrderUp();
                    mAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    /**
     * 查询当日
     */
    private void queryToady() {
        mStartTime = SCTimeUtils.getSdf_for11_01(SCTimeUtils.getFormatData11(System.currentTimeMillis())+" 00:00:00");
        mEndTime = SCTimeUtils.getSdf_for11_01(SCTimeUtils.getFormatData11(System.currentTimeMillis())+" 23:59:59");
        startQuery(mStartTime,mEndTime);
    }

    private void showDataSelect(View v) {
        vSelect = v;
        Calendar ca = Calendar.getInstance();
        int mYear = ca.get(Calendar.YEAR);
        int mMonth = ca.get(Calendar.MONTH);
        int mDay = ca.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                R.style.style_date_picker_dialog, dataListener
                , mYear, mMonth, mDay);
        datePickerDialog.show();
    }

    private void search() {
        String text = etSearch.getText().toString().trim();
        KeyboardUtils.hideSoftInput(this);
        if (TextUtils.isEmpty(text)) {
            return;
        }

        MyThreadPoolUtils.get().execute(() -> {
            // List<UserBean> list = userModel.getBeanByNameOrPhone(text);
            List<DataBean> list = dataModel.getListByNumber(text);

            runOnUiThread(() -> {
                if (list.size() > 0) {
                    mAdapter.upDatas(list);
                    mAdapter.notifyDataSetChanged();
                } else {
                    showToastTop("没有搜索到结果");
                }
            });
        });
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            //搜索
            search();
            handled = true;
        }
        return handled;
    }

    DatePickerDialog.OnDateSetListener dataListener = new DatePickerDialog.OnDateSetListener() {



        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            month++;
            String monthStr = "" + month;
            if (month < 10) {
                monthStr = "0" + month;
            }

            String dayStr = "" + dayOfMonth;
            if (dayOfMonth < 10) {
                dayStr = "0" + dayOfMonth;
            }
            //String data = "" + year + "-" + monthStr + "-" + dayStr;
            //String data = "" + year + "." + monthStr + "." + dayStr;
            //String data02 = "" + year + "-" + monthStr + "-" + dayStr;
            String data = dayStr + "/" + monthStr + "/" + year;

            if (type == 0) {
                tvStartTime.setText(data);
            }

            if (type == 1) {
                SCLogUtils.e(TAG, "22222222");
                tvEndTime.setText(data);
            }
            mStartTime = SCTimeUtils.getSdf_for11_01(tvStartTime.getText().toString()+" 00:00:00");
            mEndTime = SCTimeUtils.getSdf_for11_01(tvEndTime.getText().toString()+" 23:59:59");
            startQuery01();
        }
    };

    private void startQuery01() {

        if(mEndTime<mStartTime){
            showToastTop(R.string.sc_endtime_little_starttime);
            return;
        }
        startQuery(mStartTime, mEndTime);
    }

    private void startQuery(long startTime,long endTime) {
       //SCLogUtils.e(TAG,"startTime="+startTime);
       SCLogUtils.e(TAG,"startTime="+SCTimeUtils.getFormatData03(startTime));
       //SCLogUtils.e(TAG,"endTime="+endTime);
        SCLogUtils.e(TAG,"endTime="+SCTimeUtils.getFormatData03(endTime));
        MyThreadPoolUtils.get().execute(() -> {
            List<DataBean> list =  dataModel.getList(startTime,endTime);
            runOnUiThread(() -> {
                mAdapter.upDatas(list);
                mAdapter.notifyDataSetChanged();
                //时间降序
                vTitleDate.setOrderDown();
                isDateOrderUp = false;
            });
        });
    }

    private class CompartorOrder implements Comparator<DataBean> {
        public int type = 0;

        public CompartorOrder(int type) {
            this.type = type;
        }

        @Override
        public int compare(DataBean o1, DataBean o2) {

            switch (type) {
                case 11:
                    //日期升序
                    if (o1 != null && o2 != null) {
                        return getValue01(o1.time, o2.time);
                    }
                    break;
                case 12:
                    //日期降序
                    if (o1 != null && o2 != null) {

                        return getValue02(o1.time, o2.time);
                    }
                    break;
            }
            return 0;
        }
    }

    private int getValue01(double d01, double d02) {
        return (int) (d01 - d02);
    }

    private int getValue02(double d01, double d02) {
        return (int) (d02 - d01);
    }
}